<!DOCTYPE html>
<html>
<head>
    <title>音频可视化</title>
</head>
<body>
<input type="file" id="file-input">
<canvas id="canvas"></canvas>

<script>
    const fileInput = document.getElementById('file-input');
    const canvas = document.getElementById('canvas');
    const canvasCtx = canvas.getContext('2d');
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    fileInput.addEventListener('change', function() {
        const file = fileInput.files[0];
        const objectURL = URL.createObjectURL(file);
        const audioElement = new Audio(objectURL);
        const audioCtx = new AudioContext();
        const sourceNode = audioCtx.createMediaElementSource(audioElement);
        const analyserNode = audioCtx.createAnalyser();
        analyserNode.fftSize = 2048;

        sourceNode.connect(analyserNode);
        analyserNode.connect(audioCtx.destination);

        audioElement.addEventListener('error', function() {
            console.error('音频播放失败');
        });

        audioElement.addEventListener('ended', function() {
            console.log('音频播放结束');
        });

        audioElement.play();

        function draw() {
            requestAnimationFrame(draw);

            const dataArray = new Uint8Array(analyserNode.frequencyBinCount);
            analyserNode.getByteFrequencyData(dataArray);

            canvasCtx.fillStyle = 'rgb(0, 0, 0)';
            canvasCtx.fillRect(0, 0, canvas.width, canvas.height);

            const barWidth = canvas.width / dataArray.length;
            let x = 0;

            for (let i = 0; i < dataArray.length; i++) {
                const barHeight = canvas.height * (dataArray[i] / 255);
                canvasCtx.fillStyle = 'rgb(' + (barHeight + 100) + ',50,50)';
                canvasCtx.fillRect(x, canvas.height - barHeight, barWidth, barHeight);
                x += barWidth + 1;
            }
        }

        draw();
    });
</script>
</body>
</html>
